<template>
  <view v-if="isQuickly" class="login-form">
    <view class="form-quickly">
      <view class="login-input betweenBox">
        <view class="prefix">
          <picker
            :range="countryCodeTxtAndCodeList"
            :value="countryCodeIndex"
            class="country-code"
            @change="countryCodeChange"
          >
            <view class="picker">
              {{ countryCodeTxtList[countryCodeIndex] || '' }}
            </view>
          </picker>
        </view>
        <view class="input-warp">
          <input v-model="mobilePhone" class="ipt" placeholder="请输入手机号码" />
        </view>
        <view class="addon" @click="mobilePhone = ''">
          <server-image
            v-if="mobilePhone"
            class="del-icon"
            name="loginIcon20201020002.png"
          ></server-image>
        </view>
      </view>

      <view class="login-input betweenBox">
        <view class="input-warp">
          <input v-model="smsCode" class="ipt" placeholder="请输入验证码" />
        </view>
        <view class="addon">
          <view class="addon-warp flex-box">
            <view :class="{ deny: !allowGetCode }" class="v-code" @click="getQuicklyCode">
              <text v-if="allowGetCode">获取验证码</text>
              <text v-else>重新发送{{ countDown }}S</text>
            </view>
          </view>
        </view>
      </view>

      <view class="auto-id">推荐商家ID: {{ autoId }}</view>

      <view class="agreement">
        <view class="agreement-checkbox" @tap="agree = !agree">
          <server-image v-if="agree" class="icon" name="img20210909002.png"></server-image>
          <server-image v-else class="icon" name="img20210909001.png"></server-image>
        </view>
        <view>
          <text style="margin-left: 20rpx">我已阅读并同意</text>
          <text class="underline" @click="toRule('广州商科注册协议', 1)">《广州商科注册协议》</text>
          <text>与</text>
          <text class="underline" @click="toRule('隐私协议', 15)">《隐私协议》</text>
        </view>
      </view>

      <view class="login-submit" @click="quicklyRegister">完成注册</view>
    </view>
  </view>
  <view v-else class="login-form">
    <view class="login-tabs flex-box">
      <view :class="{ active: loginMode == 1 }" class="tab" @click="changeTab(1)">
        <view class="txt">账号密码登陆</view>
        <server-image class="tab-icon" name="loginIcon20201020001.png"></server-image>
      </view>
      <view :class="{ active: loginMode == 2 }" class="tab" @click="changeTab(2)">
        <view class="txt">手机快捷登陆</view>
        <server-image class="tab-icon" name="loginIcon20201020001.png"></server-image>
      </view>
    </view>

    <view class="form-v2">
      <view class="login-input betweenBox">
        <view class="prefix">
          <picker
            :range="countryCodeTxtAndCodeList"
            :value="countryCodeIndex"
            class="country-code"
            @change="countryCodeChange"
          >
            <view class="picker">
              {{ countryCodeTxtList[countryCodeIndex] || '' }}
            </view>
          </picker>
        </view>
        <view class="input-warp">
          <input v-model="mobilePhone" class="ipt" placeholder="请输入手机号码" />
        </view>
        <view class="addon" @click="mobilePhone = ''">
          <server-image
            v-if="mobilePhone"
            class="del-icon"
            name="loginIcon20201020002.png"
          ></server-image>
        </view>
      </view>

      <view v-if="loginMode == 1" class="login-input betweenBox">
        <view class="input-warp">
          <input
            v-model="password"
            :password="!showPassword"
            class="ipt"
            placeholder="请输入登录密码"
          />
        </view>
        <view class="addon">
          <view class="addon-warp flex-box" @tap="showPassword = !showPassword">
            <server-image
              v-if="!showPassword"
              class="visible-icon"
              name="publicInputIconHide.png"
            ></server-image>
            <server-image
              v-else
              class="visible-icon"
              name="publicInputIconDisplay.png"
            ></server-image>
          </view>
        </view>
      </view>

      <view v-if="loginMode == 2" class="login-input betweenBox">
        <view class="input-warp">
          <input v-model="imgCode" class="ipt" placeholder="请输入图形验证码" />
        </view>
        <view class="addon">
          <c-image
            :src="imgCodePath"
            class="img-code"
            mode="aspectFit"
            @click="initImgCode"
          ></c-image>
        </view>
      </view>

      <view v-if="loginMode == 2" class="login-input betweenBox">
        <view class="input-warp">
          <input v-model="smsCode" class="ipt" placeholder="请输入验证码" />
        </view>
        <view class="addon">
          <view class="addon-warp flex-box">
            <view :class="{ deny: !allowGetCode }" class="v-code" @click="getCode">
              <text v-if="allowGetCode">获取验证码</text>
              <text v-else>重新发送{{ countDown }}S</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="agreement">
      <view class="agreement-checkbox" @tap="agree = !agree">
        <server-image v-if="agree" class="icon" name="img20210909002.png"></server-image>
        <server-image v-else class="icon" name="img20210909001.png"></server-image>
      </view>
      <view>
        <text style="margin-left: 20rpx">我已阅读并同意</text>
        <text class="underline" @click="toRule('广州商科服务协议', 16)">《广州商科服务协议》</text>
        <text>与</text>
        <text class="underline" @click="toRule('隐私协议', 15)">《隐私协议》</text>
      </view>
    </view>

    <view class="login-submit" @click="login">登录</view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import config from '@/common/config';
import { isObject, encryptPassword, getSystemString } from '@/common/utils';

export default {
  name: 'LoginForm',
  props: {
    isQuickly: {
      type: Boolean,
      default: false,
    },
    autoId: Number,
  },
  data() {
    return {
      loginMode: 1,
      mobilePhone: '',
      password: '',
      countryCodeIndex: 0,
      showPassword: false,
      allowGetCode: true,
      countDown: 60,
      smsCode: '',
      imgCodePath: '',
      key: '',
      imgCode: '',
      smsCodeTimer: null,
      agree: '',
    };
  },
  computed: {
    ...mapState({
      countryCodeList: (state) => state.countryCode || [],
      systemInfo: (state) => state.systemInfo,
      systemNow: (state) => state.systemNow,
    }),
    countryCodeTxtAndCodeList: function () {
      return this.countryCodeList.map((v) => `${v.countryName} ${v.countryCode}`);
    },
    countryCodeTxtList: function () {
      return this.countryCodeList.map((v) => v.countryCode);
    },
    countryCode: function () {
      return this.countryCodeTxtList[this.countryCodeIndex];
    },
  },
  created() {
    this.getCountryList();
  },
  methods: {
    ...mapActions(['getCountryList']),
    countryCodeChange(e) {
      this.countryCodeIndex = e.detail.value;
    },
    async changeTab(tab) {
      if (tab == this.loginMode) return;
      this.smsCode = '';
      this.password = '';
      await this.sleep(100);
      this.initImgCode();
      this.loginMode = tab;
    },
    login() {
      if (this.loginMode == 1) this.psdLogin();
      else this.smsLogin();
    },
    checkField(params, type) {
      return new Promise((resolve, reject) => {
        if (type === 'psd') {
          if (!params.mobilePhone) return reject(new Error('请输入手机号码'));
          if (!params.password) return reject(new Error('请输入登录密码'));
          if (!params.agree)
            return reject(new Error('请先阅读并同意【广州商科服务协议】与【隐私协议】'));
        }
        if (type === 'sms') {
          if (!params.mobilePhone) return reject(new Error('请输入手机号码'));
          if (!params.imgCode) return reject(new Error('请输入图片验证码'));
          if (!params.smsCode) return reject(new Error('请输入短信验证码'));
          if (!params.agree)
            return reject(new Error('请先阅读并同意【广州商科服务协议】与【隐私协议】'));
        }
        if (type === 'quickly') {
          if (!params.mobilePhone) return reject(new Error('请输入手机号码'));
          if (!params.smsCode) return reject(new Error('请输入短信验证码'));
          if (!params.agree)
            return reject(new Error('请先阅读并同意【广州商科注册协议】与【隐私协议】'));
        }
        return resolve();
      });
    },
    psdLogin() {
      const params = {
        mobilePhone: this.mobilePhone,
        countryCode: this.countryCode,
        agree: this.agree,
      };

      if (this.password) {
        params.password = encryptPassword(this.password);
      }

      this.checkField(params, 'psd')
        .then(() => {
          this.apiUrl.login({ data: params }).then((res) => {
            let message = null;
            const { status, message: rMessage, data: rData } = res.data;
            if (status != 1) {
              const msgDic = {
                0: '手机号不存在',
                2: '密码错误',
                3: '会员被禁用',
              };
              message = msgDic[status] || rMessage || '未知错误';
            }

            if (message) {
              this.showMessage({ title: message });
            } else {
              this.loginSuccess(rData);
            }
          });
        })
        .catch((e) => {
          this.showMessage({ title: e.message });
        });
    },
    smsLogin() {
      const params = {
        mobilePhone: this.mobilePhone,
        smsCode: this.smsCode,
        countryCode: this.countryCode,
        imgCode: this.imgCode,
        agree: this.agree,
      };

      this.checkField(params, 'sms')
        .then(() => {
          this.apiUrl.memberSmsLogin({ data: params }).then((res) => {
            let message = null;
            const { status, message: rMessage, data: rData } = res.data;
            if (status != 1) {
              const msgDic = {
                3: '会员被禁用',
              };
              message = msgDic[status] || rMessage || '未知错误';
            }

            if (message) {
              this.showMessage({ title: message });
            } else {
              this.loginSuccess(rData);
            }
          });
        })
        .catch((e) => {
          this.showMessage({ title: e.message });
        });
    },
    loginSuccess(res, msg) {
      this.$emit('login-success', res, msg);
    },
    getCode() {
      if (!this.allowGetCode) return;
      if (!this.mobilePhone) {
        this.showMessage({ title: '请输入手机号码' });
        return;
      }

      if (!this.imgCode) {
        this.showMessage({ title: '请输入图片验证码' });
        return;
      }

      this.allowGetCode = false;
      this.timeCountdown();

      const params = {
        countryCode: this.countryCode,
        mobilePhone: this.mobilePhone,
        verifyCode: this.imgCode,
        key: this.key,
      };

      this.apiUrl
        .memberGetLoginSMSCaptcha({ data: params })
        .then((res) => {
          if (res.data.code == 0) {
            this.allowGetCode = false;
            this.showMessage({ title: '验证码已发送' });
            return;
          }
          return Promise.reject(res);
        })
        .catch((err) => {
          this.allowGetCode = true;
          clearTimeout(this.smsCodeTimer);
          this.initImgCode();

          if (!isObject(err)) return;

          if (err.data.status == 'timeout') {
            this.showMessage({ title: '获取验证码失败' });
            return;
          }

          this.showMessage({ title: err.data.message });
        });
    },
    getQuicklyCode() {
      if (!this.allowGetCode) return;
      if (!this.mobilePhone) {
        this.showMessage({ title: '请输入手机号码' });
        return;
      }

      this.allowGetCode = false;
      this.timeCountdown();

      const params = {
        type: 1,
        mobilePhone: this.mobilePhone,
        timestamp: this.systemNow,
        systemDigest: getSystemString(this.systemInfo.wgtVersion, this.systemNow),
      };

      this.apiUrl
        .memberGetSMSCode({ data: params })
        .then((res) => {
          if (res.data.code == 0) {
            this.allowGetCode = false;
            this.showMessage({ title: '验证码已发送' });
            return;
          }
          return Promise.reject(res);
        })
        .catch((err) => {
          this.allowGetCode = true;
          clearTimeout(this.smsCodeTimer);
          this.initImgCode();

          if (!isObject(err)) return;

          if (err.data.status == 'timeout') {
            this.showMessage({ title: '获取验证码失败' });
            return;
          }

          this.showMessage({ title: err.data.message });
        });
    },
    timeCountdown() {
      if (!this.countDown) {
        this.countDown = 60;
        clearTimeout(this.smsCodeTimer);
        this.allowGetCode = true;
        return;
      }
      this.countDown--;
      this.smsCodeTimer = setTimeout(() => {
        this.timeCountdown();
      }, 1000);
    },
    initImgCode() {
      this.key = new Date().getTime();
      this.imgCodePath = config.baseUrl + '/member_veryCode.action?key=' + this.key;
      this.imgCode = '';
    },
    checkAgree() {
      return this.checkField({ agree: this.agree });
    },
    quicklyRegister() {
      const params = {
        mobilePhone: this.mobilePhone,
        smsCode: this.smsCode,
        parent: this.autoId,
        agree: this.agree,
      };

      this.checkField(params, 'quickly')
        .then(() => {
          this.apiUrl.memberFastReg({ data: params }).then((res) => {
            let message = null;
            const { status, message: rMessage, data: rData } = res.data;
            if (status != 1) {
              const msgDic = {
                3: '会员被禁用',
              };
              message = msgDic[status] || rMessage || '未知错误';
            }

            if (message) {
              this.showMessage({ title: message });
            } else {
              this.loginSuccess(rData, rMessage);
            }
          });
        })
        .catch((e) => {
          this.showMessage({ title: e.message });
        });
    },
  },
};
</script>

<style lang="less" scoped>
.img-code {
  width: 150rpx;
  height: 70rpx;
  display: block;
  overflow: hidden;
}

.login-tabs {
  margin-bottom: 44rpx;

  .tab {
    flex: 1;

    &.active {
      .txt {
        color: #696969;
      }

      .tab-icon {
        opacity: 1;
      }
    }
  }

  .txt {
    text-align: center;
    height: 45rpx;
    font-size: 32rpx;
    font-weight: 400;
    color: #cecece;
    line-height: 45rpx;
  }
}

.tab-icon {
  width: 11px;
  height: 6px;
  display: block;
  opacity: 0;
  overflow: hidden;
  margin: 20rpx auto 0;
}

.login-submit {
  height: 90rpx;
  background: #e64e2d;
  border-radius: 45px;
  line-height: 90rpx;

  font-size: 36rpx;
  color: #fff;
  line-height: 50rpx;
  line-height: 90rpx;
  margin-top: 100rpx;
  text-align: center;
}

.v-code {
  height: 37rpx;
  line-height: 37rpx;

  text {
    font-size: 26rpx;
    color: #959595;
  }

  &.deny text {
    color: #b4b1aa;
  }
}

.country-code {
  height: 40rpx;
  border-right: 1px solid #b4b1aa;
  padding-right: 24rpx;
  margin-right: 24rpx;
  min-width: 88rpx;
  box-sizing: border-box;

  .picker {
    font-size: 34rpx;
    font-weight: 400;
    color: #333333;
    line-height: 40rpx;
  }
}

.agreement {
  display: flex;
  align-items: center;

  text {
    color: #656565;
    height: 40rpx;
    font-size: 24rpx;
    line-height: 40rpx;
    overflow: hidden;
  }

  .underline {
    color: #e64e2d;
    text-decoration: underline;
  }
}

.agreement-checkbox .icon {
  width: 32rpx;
  height: 32rpx;
  display: block;
}

.auto-id {
  width: 264rpx;
  height: 42rpx;
  font-size: 30rpx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #999999;
  line-height: 42rpx;
  margin-bottom: 48rpx;
  margin-top: 38rpx;
}

.form-quickly {
  .login-input {
    height: 134rpx;
    box-sizing: border-box;
    padding-right: 30rpx;
    border-bottom: 1rpx solid #f4f4f4;
  }

  .input-warp {
    flex: 1;

    .ipt {
      height: 48rpx;
      font-size: 34rpx;
      font-weight: 400;
      color: #333333;
      line-height: 48rpx;
    }
  }

  .del-icon {
    width: 30rpx !important;
    height: 30rpx !important;
    display: block;
    overflow: hidden;
  }

  .addon-warp {
    height: 40rpx;
    padding-left: 28rpx;
    border-left: 1px solid #b4b1aa;
  }
}
</style>
